package com.xiashitech.agent.instrumentation.db.statement.inst;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.constants.Instrumentation;
import com.xiashitech.agent.instrumentation.db.common.XSResultSizeContext;
import com.xiashitech.agent.instrumentation.helper.calldepth.XSStatementCallDepth;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.utils.DurationPrinter;
import io.opentelemetry.javaagent.bootstrap.CallDepth;
import io.opentelemetry.javaagent.bootstrap.internal.InstrumentationConfig;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import io.opentelemetry.javaagent.shaded.instrumentation.jdbc.internal.DbRequest;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Scope;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

import java.sql.Statement;

import static com.xiashitech.agent.instrumentation.db.statement.XSJdbcSingletons.jdbcInstrumenter;
import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;
import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.hasClassesNamed;
import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.implementsInterface;
import static net.bytebuddy.matcher.ElementMatchers.*;

public class XSStatementInstrumentation implements TypeInstrumentation {
    @Override
    public ElementMatcher<ClassLoader> classLoaderOptimization() {
        return hasClassesNamed("java.sql.Statement");
    }

    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        return implementsInterface(named("java.sql.Statement"));
    }

    @Override
    public void transform(TypeTransformer transformer) {
        transformer.applyAdviceToMethod(
                nameStartsWith("execute").and(takesArgument(0, String.class))
                        .and(takesArguments(1))
                        .and(isPublic()),
                XSStatementInstrumentation.class.getName() + "$XSStatementAdvice");
    }

    @SuppressWarnings("unused")
    public static class XSStatementAdvice {

        @Advice.OnMethodEnter(suppress = Throwable.class)
        public static void onEnter(
                @Advice.Argument(0) String sql,
                @Advice.This Statement statement,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelRequest") DbRequest request,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
//            if(statement != null && statement.getClass().getName().startsWith("xiashitech.shade.extload")) {
//                return;
//            }
            DurationPrinter durationPrinter = new DurationPrinter("XSStatementInstrumentation");
            if(CacheStatus.cannotRun()) {
                return;
            }
            String suppressSpecialsql = InstrumentationConfig.get().getString("xs.suppress.specialsql", Instrumentation.DEFAULT_SUPPRESS_SQL);
            if(!suppressSpecialsql.contains(Instrumentation.DEFAULT_SUPPRESS_SQL)) {
                suppressSpecialsql += ","+Instrumentation.DEFAULT_SUPPRESS_SQL;
            }
            if(sql != null && suppressSpecialsql.contains(sql)) {
                return;
            }
            callDepth = CallDepth.forClass(XSStatementCallDepth.class);
            if (callDepth.getAndIncrement() > 0) {
                return;
            }
            Context parentContext = currentContext();
            request = DbRequest.create(statement,sql);
            if (request == null || !jdbcInstrumenter().shouldStart(parentContext, request)) {
                return;
            }
            try {
                parentContext = BaggageUtil.syncBaggage().build().storeInContext(parentContext);
                context = jdbcInstrumenter().start(parentContext, request);
                context = BaggageUtil.syncBaggage().build().storeInContext(context);
            } catch (Throwable e) {
                StartConfig.throwableStackPrinter(e);
            }
            scope = context.makeCurrent();
            XSResultSizeContext.addStatementSQLContext(XSResultSizeContext.StatementSQLContext.builder().statement(statement).sql(sql).build());
            durationPrinter.printElapseDuration("XSStatementAdvice b");
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
        public static void onExit(
                @Advice.Argument(0) String sql,
                @Advice.This Statement statement,
                @Advice.Thrown Throwable throwable,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelRequest") DbRequest request,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
//            if(statement != null && statement.getClass().getName().startsWith("xiashitech.shade.extload")) {
//                return;
//            }
            DurationPrinter durationPrinter = new DurationPrinter("XSStatementInstrumentation");
            if(CacheStatus.cannotRun()) {
                return;
            }
            String suppressSpecialsql = InstrumentationConfig.get().getString("xs.suppress.specialsql", Instrumentation.DEFAULT_SUPPRESS_SQL);
            if(!suppressSpecialsql.contains(Instrumentation.DEFAULT_SUPPRESS_SQL)) {
                suppressSpecialsql += ","+Instrumentation.DEFAULT_SUPPRESS_SQL;
            }
            if(sql != null && suppressSpecialsql.contains(sql)) {
                return;
            }
            if (callDepth.decrementAndGet() > 0) {
                return;
            }
            if (scope != null) {
                scope.close();
                jdbcInstrumenter().end(context, request, null, throwable);
            }
            durationPrinter.printElapseDuration("XSStatementAdvice e");
        }
    }
}
